<template>
  <div class="product-container">
    <el-card>
      <div class="card-header">
        <h2>商品列表</h2>
        <el-button type="primary" @click="handleAdd">
          <el-icon><plus /></el-icon>
          添加商品
        </el-button>
      </div>

      <!-- 搜索条件 -->
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item label="商品名称">
          <el-input v-model="searchForm.nameLike" placeholder="请输入商品名称" clearable></el-input>
        </el-form-item>
        <el-form-item label="商品类别">
          <el-select
              v-model="searchForm.categoryId"
              placeholder="请选择商品类别"
              clearable>
            <el-option
                v-for="category in categoryList"
                :key="category.categoryId"
                :label="category.name"
                :value="category.categoryId">
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="供应商">
          <el-select
              v-model="searchForm.supplierId"
              placeholder="请选择供应商"
              clearable>
            <el-option
                v-for="supplier in supplierList"
                :key="supplier.supplierId"
                :label="supplier.name"
                :value="supplier.supplierId">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="商品类型">
          <el-select v-model="searchForm.type" placeholder="请选择类型" clearable>
            <el-option label="成品" value="1"></el-option>
            <el-option label="次品" value="2"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="商品状态">
          <el-select v-model="searchForm.status" placeholder="请选择状态" clearable>
            <el-option label="启用" value="1"></el-option>
            <el-option label="禁用" value="0"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="resetForm">重置</el-button>
        </el-form-item>
      </el-form>

      <!-- 商品列表 -->
      <el-table :data="productList" border style="width: 100%">
        <el-table-column type="index" label="序号" width="80"></el-table-column>
        <el-table-column prop="name" label="商品名称" width="80"></el-table-column>
        <el-table-column label="商品图片" width="120">
          <template #default="scope">
            <el-image
                :src="getImageUrl(scope.row.imgSrc)"
            :preview-src-list="[getImageUrl(scope.row.imgSrc)]"
            fit="cover"
            width="60"
            height="60">
            <!-- 加载失败时显示的占位图 -->
            <template #error>
              <div class="image-placeholder">
                <el-icon><picture /></el-icon>
              </div>
            </template>
            </el-image>
          </template>
        </el-table-column>
        <el-table-column label="商品类别" width="80">
          <template #default="scope">
            {{ getCategoryName(scope.row.categoryId) }}
          </template>
        </el-table-column>
        <el-table-column label="供应商" width="180">
          <template #default="scope">
            {{ getSupplierName(scope.row.supplierId) }}
          </template>
        </el-table-column>
        <el-table-column prop="price" label="价格" width="100">
          <template #default="scope">{{ formatPrice(scope.row.price) }}</template>
        </el-table-column>
        <el-table-column prop="stock" label="库存" width="100"></el-table-column>
        <el-table-column prop="type" label="类型" width="100">
          <template #default="scope">
            <el-tag :type="scope.row.type === '1' ? 'success' : 'danger'">
              {{ scope.row.type === '1' ? '成品' : '次品' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template #default="scope">
            <el-tag :type="scope.row.status === '1' ? 'success' : 'danger'">
              {{ scope.row.status === '1' ? '启用' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="240">
          <template #default="scope">
            <el-button size="small" type="primary" @click="handleEdit(scope.row)">编辑</el-button>
            <el-button size="small" type="danger" @click="handleDelete(scope.row.productId)">删除</el-button>
            <el-button
                :type="scope.row.status === '0' ? 'success' : 'warning'"
                size="small"
                @click="handleStatusChange(scope.row)"
            >
              {{ scope.row.status === '1' ? '下架' : '上架' }}
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="pageNum"
            :page-sizes="[5, 10, 20, 50]"
            :page-size="pageSize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total">
        </el-pagination>
      </div>
    </el-card>

    <!-- 添加/编辑商品弹窗 -->
    <el-dialog v-model="dialogVisible" :title="dialogTitle" width="60%">
      <el-form :model="form" :rules="rules" ref="formRef" label-width="120px">
        <!-- 商品名称选择/输入 -->
        <el-form-item label="商品名称" prop="name">
          <template v-if="dialogTitle === '添加商品'">
            <el-select
                v-model="selectedProductId"
                placeholder="请从成品中选择商品"
                clearable
                filterable
                @change="handleProductChange"
            >
              <el-option
                  v-for="product in allFinishedProducts"
                  :key="product.productId"
                  :label="product.name"
                  :value="product.productId"
              ></el-option>
            </el-select>
          </template>
          <template v-else>
            <el-input v-model="form.name" placeholder="请输入商品名称"></el-input>
          </template>
          <!-- 调试信息：显示当前选中的商品ID -->
          <div class="debug-info" v-if="debugMode && dialogTitle === '添加商品'">
            选中的商品ID: {{ selectedProductId }}
          </div>
        </el-form-item>

        <el-form-item label="商品类别" prop="categoryId">
          <el-select v-model="form.categoryId" placeholder="请选择商品类别">
            <el-option v-for="category in categoryList" :key="category.categoryId"
                       :label="category.name" :value="category.categoryId"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="供应商" prop="supplierId">
          <el-select v-model="form.supplierId" placeholder="请选择供应商">
            <el-option v-for="supplier in supplierList" :key="supplier.supplierId"
                       :label="supplier.name" :value="supplier.supplierId"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="主单位" prop="unitId">
          <el-select v-model="form.unitId" placeholder="请选择主单位">
            <el-option v-for="unit in unitList" :key="unit.unitId"
                       :label="unit.name" :value="unit.unitId"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="分量单位" prop="secondUnitId">
          <el-select v-model="form.secondUnitId" placeholder="请选择分量单位">
            <el-option v-for="unit in unitList" :key="unit.unitId"
                       :label="unit.name" :value="unit.unitId"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="换算比例" prop="convert">
          <el-input v-model="form.convert" placeholder="请输入换算比例"></el-input>
        </el-form-item>
        <el-form-item label="商品图片">
          <el-upload
              class="avatar-uploader"
              action="/api/product/upload"
              :show-file-list="false"
              :on-success="handleUploadSuccess"
              :before-upload="beforeUpload">
            <img v-if="form.imgSrc" :src="form.imgSrc" class="avatar"/>
            <el-icon v-else class="avatar-uploader-icon">
              <plus/>
            </el-icon>
          </el-upload>
        </el-form-item>
        <el-form-item label="商品类型" prop="type">
          <el-radio-group v-model="form.type" @change="handleProductTypeChange">
            <el-radio label="1">成品</el-radio>
            <el-radio label="2">次品</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="价格" prop="price">
          <el-input v-model="form.price" placeholder="请输入价格"></el-input>
        </el-form-item>
        <el-form-item label="库存" prop="stock">
          <el-input v-model="form.stock" placeholder="请输入库存"></el-input>
        </el-form-item>
        <el-form-item label="最小库存" prop="minStock">
          <el-input v-model="form.minStock" placeholder="请输入最小库存"></el-input>
        </el-form-item>
        <el-form-item label="最大库存" prop="maxStock">
          <el-input v-model="form.maxStock" placeholder="请输入最大库存"></el-input>
        </el-form-item>
        <el-form-item label="损耗率" prop="lossRate">
          <el-input v-model="form.lossRate" placeholder="请输入损耗率"></el-input>
        </el-form-item>
        <el-form-item label="商品状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio label="1">启用（上架）</el-radio>
            <el-radio label="0">禁用（下架）</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import {Plus} from '@element-plus/icons-vue';
import {getProductList, deleteProduct, addProduct, updateProduct, getProductById} from '../api/product';
import {ElMessage, ElMessageBox, ElLoading} from 'element-plus';
import {getAllSuppliers} from "../api/supplier.js";
import {findAllApi} from "../api/unit.js";
import {findAll2} from "../api/categoryApi.js";
// 导入findAllVO接口用于获取成品入库商品列表
import {findAllVO, checkProductExists, updateProductStock} from '../api/productInput.js';

export default {
  name: 'ProductManagement',
  components: {
    Plus
  },
  data() {
    return {
      // 调试模式开关，用于显示调试信息
      debugMode: true,

      // 搜索表单
      searchForm: {
        nameLike: '',
        categoryId: null,
        supplierId: null,
        type: '',
        status: null
      },

      // 商品列表数据
      allProducts: [],
      productList: [],

      // 基础数据列表
      categoryList: [],
      supplierList: [],
      unitList: [],

      // 成品相关数据，从findAllVO接口获取
      allFinishedProducts: [],        // 所有成品，用于下拉列表
      selectedProductId: '',          // 选中的成品ID
      selectedProduct: null,          // 选中的成品完整信息

      // 分页相关
      total: 0,
      pageNum: 1,
      pageSize: 10,

      // 弹窗相关
      dialogVisible: false,
      dialogTitle: '添加商品',

      // 表单数据
      form: {
        productId: '',
        name: '',
        categoryId: '',
        supplierId: '',
        unitId: '',
        secondUnitId: '',
        convert: 1,
        imgSrc: '',
        type: '1', // 默认是成品
        price: '',
        stock: '',
        minStock: '',
        maxStock: '',
        lossRate: '',
        status: '1', // 默认上架状态
        finishedProductId: '' // 关联成品ID
      },

      // 表单验证规则
      rules: {
        name: [
          {required: true, message: '请选择或输入商品名称', trigger: 'change, blur'}
        ],
        categoryId: [
          {required: true, message: '请选择商品类别', trigger: 'change'}
        ],
        supplierId: [
          {required: true, message: '请选择供应商', trigger: 'change'}
        ],
        unitId: [
          {required: true, message: '请选择主单位', trigger: 'change'}
        ],
        price: [
          {required: true, message: '请输入价格', trigger: 'blur'},
          {type: 'number', message: '请输入数字', trigger: 'blur'}
        ],
        stock: [
          {required: true, message: '请输入库存', trigger: 'blur'},
          {type: 'number', message: '请输入数字', trigger: 'blur'}
        ],
        status: [
          {required: true, message: '请选择商品状态', trigger: 'change'}
        ]
      }
    };
  },
  mounted() {
    this.loadAllData();
  },
  methods: {
    /**
     * 统一加载所有必要数据
     */
    async loadAllData() {
      const loading = ElLoading.service({
        lock: true,
        text: '数据加载中...',
        background: 'rgba(0, 0, 0, 0.7)'
      });

      try {
        await Promise.all([
          this.getCategories(),
          this.getSuppliers(),
          this.getUnits(),
          this.loadFinishedProducts() // 加载成品数据
        ]);
        await this.getAllProducts();
        this.filterProducts();

        // 调试信息：显示成品列表加载结果
        if (this.debugMode) {
          console.log('成品列表加载完成，共', this.allFinishedProducts.length, '条数据');
          console.log('成品列表数据:', this.allFinishedProducts);
        }
      } catch (error) {
        console.error('数据加载失败', error);
        ElMessage.error('数据加载失败，请刷新页面重试');
      } finally {
        loading.close();
      }
    },

    /**
     * 加载成品数据 - 通过findAllVO接口获取，用于下拉列表
     */
    async loadFinishedProducts() {
      try {
        // 使用findAllVO接口获取成品入库商品列表
        const {data} = await findAllVO();

        // 详细的响应检查
        if (!data) {
          throw new Error('未收到响应数据');
        }

        if (data.code !== 200) {
          throw new Error(`接口返回错误: ${data.msg || '未知错误'}`);
        }

        if (!Array.isArray(data.data)) {
          throw new Error(`成品数据不是数组，实际类型: ${typeof data.data}`);
        }

        // 保存原始数据用于调试
        if (this.debugMode) {
          console.log('原始成品数据:', data.data);
        }

        // 标准化成品数据格式，确保ID为字符串类型
        this.allFinishedProducts = data.data.map(product => ({
          ...product,
          productId: String(product.productId || product.id), // 兼容可能的id字段
          categoryId: String(product.categoryId),
          supplierId: String(product.supplierId),
          unitId: String(product.unitId),
          num: product.num !== undefined ? product.num : product.stock, // 兼容可能的stock字段
          price: product.price || 0,
          name: product.name || '未知商品'
        }));

        ElMessage.success(`成功加载 ${this.allFinishedProducts.length} 个成品`);
      } catch (error) {
        console.error('加载成品数据失败:', error.message, error);
        ElMessage.error(`加载成品数据失败: ${error.message}`);
        this.allFinishedProducts = [];
        throw error;
      }
    },

    /**
     * 处理商品选择变化
     */
    handleProductChange(productId) {
      // 清空之前的选择
      if (!productId) {
        this.selectedProduct = null;
        this.form.name = '';
        this.form.stock = '';
        this.form.categoryId = '';
        this.form.supplierId = '';
        this.form.unitId = '';
        this.form.price = '';
        this.form.imgSrc = '';
        this.form.finishedProductId = '';

        if (this.debugMode) {
          console.log('已清空商品选择');
        }
        return;
      }

      // 调试信息：显示当前选择的productId
      if (this.debugMode) {
        console.log('选择的商品ID:', productId, '类型:', typeof productId);
      }

      // 查找选中的商品信息 - 考虑类型转换问题
      const selectedProduct = this.allFinishedProducts.find(
          product => product.productId === productId
      );

      // 未找到对应商品的处理
      if (!selectedProduct) {
        ElMessage.warning('未找到对应的商品信息');
        console.warn('未找到ID为', productId, '的商品，可用商品ID:', this.allFinishedProducts.map(p => p.productId));

        // 清空表单相关字段
        this.form.name = '';
        this.form.stock = '';
        this.form.categoryId = '';
        this.form.supplierId = '';
        this.form.unitId = '';
        this.form.price = '';
        this.form.finishedProductId = '';
        return;
      }

      // 调试信息：显示找到的商品信息
      if (this.debugMode) {
        console.log('找到的商品信息:', selectedProduct);
      }

      // 保存选中的商品信息
      this.selectedProduct = selectedProduct;

      // 核心映射：选择的商品数据 -> 表单数据
      this.form.name = selectedProduct.name;
      this.form.finishedProductId = selectedProduct.productId;
      this.form.categoryId = selectedProduct.categoryId;
      this.form.supplierId = selectedProduct.supplierId;
      this.form.unitId = selectedProduct.unitId;
      this.form.price = selectedProduct.price;
      this.form.imgSrc = selectedProduct.imgSrc || '';
      this.form.stock = Number(selectedProduct.num) || 0;

      ElMessage.success(`已选择商品：${selectedProduct.name}，相关信息已自动填充`);
    },

    /**
     * 处理商品类型变更
     */
    handleProductTypeChange(type) {
      if (this.debugMode) {
        console.log('商品类型变更为:', type);
      }
    },

    /**
     * 获取分类列表
     */
    async getCategories() {
      try {
        const {data} = await findAll2();
        if (data.code === 200 && Array.isArray(data.data)) {
          this.categoryList = data.data.map(category => ({
            ...category,
            categoryId: String(category.categoryId)
          }));
        } else {
          this.categoryList = [];
          ElMessage.error('获取分类列表失败: 返回数据格式不正确');
        }
      } catch (error) {
        console.error('获取分类列表失败', error);
        ElMessage.error('获取分类列表失败');
        throw error;
      }
    },

    /**
     * 获取全部商品
     */
    async getAllProducts() {
      try {
        const {data} = await getProductList();

        console.log(data)
        if (data.code === 200 && Array.isArray(data.data)) {
          this.allProducts = data.data.map(product => ({
            ...product,
            categoryId: String(product.categoryId),
            supplierId: String(product.supplierId),
            type: String(product.type),
            status: String(product.status)
          }));
        } else {
          this.allProducts = [];
          ElMessage.error('获取商品列表失败: 返回数据格式不正确');
        }
      } catch (error) {
        console.error('获取全部商品失败', error);
        ElMessage.error('获取商品列表失败');
        throw error;
      }
    },

    /**
     * 过滤商品列表
     */
    filterProducts() {
      let filtered = [...this.allProducts];

      // 1. 商品名称模糊过滤
      if (this.searchForm.nameLike) {
        const keyword = this.searchForm.nameLike.toLowerCase();
        filtered = filtered.filter(item =>
            item.name && item.name.toLowerCase().includes(keyword)
        );
      }

      // 2. 商品类别过滤
      if (this.searchForm.categoryId !== null) {
        const targetCategoryId = String(this.searchForm.categoryId);
        filtered = filtered.filter(item => item.categoryId === targetCategoryId);
      }

      // 3. 供应商过滤
      if (this.searchForm.supplierId !== null) {
        const targetSupplierId = String(this.searchForm.supplierId);
        filtered = filtered.filter(item => item.supplierId === targetSupplierId);
      }

      // 4. 商品类型过滤
      if (this.searchForm.type) {
        filtered = filtered.filter(item => item.type === this.searchForm.type);
      }

      // 5. 商品状态过滤
      if (this.searchForm.status !== null) {
        const targetStatus = String(this.searchForm.status);
        filtered = filtered.filter(item => item.status === targetStatus);
      }

      // 处理分页
      this.total = filtered.length;
      const startIndex = (this.pageNum - 1) * this.pageSize;
      const endIndex = startIndex + this.pageSize;
      this.productList = filtered.slice(startIndex, endIndex);
    },

    /**
     * 搜索按钮点击事件
     */
    handleSearch() {
      this.pageNum = 1;
      this.filterProducts();
    },

    /**
     * 重置搜索表单
     */
    resetForm() {
      this.searchForm = {
        nameLike: '',
        categoryId: null,
        supplierId: null,
        type: '',
        status: null
      };
      this.pageNum = 1;
      this.filterProducts();
    },

    /**
     * 分页大小改变
     */
    handleSizeChange(val) {
      this.pageSize = val;
      this.pageNum = 1;
      this.filterProducts();
    },

    /**
     * 当前页改变
     */
    handleCurrentChange(val) {
      this.pageNum = val;
      this.filterProducts();
    },

    /**
     * 价格格式化
     */
    formatPrice(price) {
      if (!price && price !== 0) return '¥0.00';
      return '¥' + Number(price).toFixed(2);
    },

    /**
     * 根据categoryId获取类别名称
     */
    getCategoryName(categoryId) {
      if (!this.categoryList.length) {
        return "加载中...";
      }
      const category = this.categoryList.find(
          item => item.categoryId === categoryId
      );
      return category ? category.name : "未知类别";
    },

    /**
     * 根据supplierId获取供应商名称
     */
    getSupplierName(supplierId) {
      if (!this.supplierList || this.supplierList.length === 0) {
        return "加载中...";
      }
      const supplier = this.supplierList.find(
          item => String(item.supplierId) === String(supplierId)
      );
      return supplier ? supplier.name : "未知供应商";
    },

    /**
     * 获取供应商列表
     */
    async getSuppliers() {
      try {
        const {data} = await getAllSuppliers();
        if (data.code === 200) {
          this.supplierList = data.data.map(supplier => ({
            ...supplier,
            supplierId: String(supplier.supplierId)
          })) || [];
        } else {
          ElMessage.error('获取供应商列表失败: ' + (data.msg || '未知错误'));
        }
      } catch (error) {
        console.error('获取供应商列表失败', error);
        ElMessage.error('获取供应商列表失败');
        throw error;
      }
    },

    /**
     * 获取单位列表
     */
    async getUnits() {
      try {
        const {data} = await findAllApi();
        if (data.code === 200) {
          this.unitList = data.data || [];
        } else {
          ElMessage.error('获取单位列表失败: ' + (data.msg || '未知错误'));
        }
      } catch (error) {
        console.error('获取单位列表失败', error);
        ElMessage.error('获取单位列表失败');
        throw error;
      }
    },

    /**
     * 添加商品
     */
    handleAdd() {
      this.dialogTitle = '添加商品';
      if (this.$refs.formRef) {
        this.$refs.formRef.resetFields();
      }
      // 重置表单数据
      this.form = {
        productId: '',
        name: '',
        categoryId: '',
        supplierId: '',
        unitId: '',
        secondUnitId: '',
        convert: 1,
        imgSrc: '',
        type: '1',
        price: '',
        stock: '',
        minStock: '',
        maxStock: '',
        lossRate: '',
        status: '1', // 默认上架
        finishedProductId: ''
      };
      // 重置商品选择相关字段
      this.selectedProductId = '';
      this.selectedProduct = null;

      this.dialogVisible = true;
    },

    /**
     * 编辑商品 - 修复版
     */
    async handleEdit(row) {
      this.dialogTitle = '编辑商品';
      try {
        const {data} = await getProductById(row.productId);
        if (data.code === 200) {
          const product = data.data;

          // 填充表单数据，确保所有ID为字符串类型，避免类型不匹配
          this.form = {
            ...product,
            status: String(product.status),
            type: String(product.type),
            categoryId: String(product.categoryId),
            supplierId: String(product.supplierId),
            unitId: String(product.unitId),
            secondUnitId: product.secondUnitId ? String(product.secondUnitId) : '',
            finishedProductId: product.finishedProductId ? String(product.finishedProductId) : ''
          };

          // 编辑模式不需要选中商品下拉项，因此重置选择器
          this.selectedProductId = '';
          this.selectedProduct = null;

          this.dialogVisible = true;
        } else {
          ElMessage.error('获取商品详情失败: ' + (data.msg || '未知错误'));
        }
      } catch (error) {
        console.error('获取商品详情失败', error);
        ElMessage.error('获取商品详情失败');
      }
    },

    /**
     * 删除商品
     */
    async handleDelete(productId) {
      try {
        const confirm = await ElMessageBox.confirm(
            '确定要删除该商品吗？此操作不可撤销！',
            '删除确认',
            {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning'
            }
        );

        if (confirm === 'confirm') {
          const {data} = await deleteProduct(productId);
          if (data.code === 200) {
            ElMessage.success('删除成功');
            await this.getAllProducts();
            this.filterProducts();
          } else {
            ElMessage.error(data.msg || '删除失败');
          }
        }
      } catch (error) {
        if (error === 'cancel') return;
        console.error('删除商品失败', error);
        ElMessage.error('删除失败');
      }
    },

    /**
     * 上架/下架商品
     */
    async handleStatusChange(row) {
      const action = row.status === '1' ? '下架' : '上架';
      try {
        const confirm = await ElMessageBox.confirm(
            `确定要将该商品${action}吗？`,
            '状态变更确认',
            {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: action === '下架' ? 'warning' : 'success'
            }
        );

        if (confirm === 'confirm') {
          // 调用更新接口修改状态
          const {data} = await updateProduct({
            productId: row.productId,
            status: row.status === '1' ? 0 : 1
          });

          if (data.code === 200) {
            ElMessage.success(`${action}成功`);
            await this.getAllProducts();
            this.filterProducts();
          } else {
            ElMessage.error(data.msg || `${action}失败`);
          }
        }
      } catch (error) {
        if (error === 'cancel') return;
        console.error(`${action}商品失败`, error);
        ElMessage.error(`${action}失败`);
      }
    },

    /**
     * 提交表单（添加/编辑）- 修复版
     */
    async handleSubmit() {
      try {
        await this.$refs.formRef.validate();

        // 编辑模式直接提交，不检查商品是否存在
        if (this.form.productId) {
          const res = await updateProduct(this.form);
          const data = res.data;

          if (data.code === 200) {
            ElMessage.success('更新成功');
            this.dialogVisible = false;
            await this.getAllProducts();
            this.filterProducts();
          } else {
            ElMessage.error(data.msg || '更新失败');
          }
          return;
        }

        // 添加模式逻辑
        if (this.selectedProduct) {
          // 检查商品是否已存在
          const {data} = await checkProductExists(this.selectedProduct.productId);
          console.log(data)
          if (data.code === 200) {
            // 商品已存在，更新库存
            const productId = data.data.productId;
            const currentStock = Number(data.data.stock) || 0;
            const addStock = Number(this.selectedProduct.num) || 0;
            const newStock = currentStock + addStock;

            // 显示确认信息
            await ElMessageBox.confirm(
                `商品"${this.form.name}"已存在，当前库存为${currentStock}。是否将库存更新为${newStock}？`,
                '商品已存在',
                {
                  confirmButtonText: '确定',
                  cancelButtonText: '取消',
                  type: 'info'
                }
            );

            // 执行库存更新
            const {data: updateRes} = await updateProductStock({
              productId,
              stock: newStock
            });

            if (updateRes.code === 200) {
              ElMessage.success('商品库存已更新');
              this.dialogVisible = false;
              await this.getAllProducts();
              this.filterProducts();
              return;
            }
          }
        }

        // 新增商品
        const res = await addProduct(this.form);
        const data = res.data;

        if (data.code === 200) {
          ElMessage.success('添加成功');
          this.dialogVisible = false;
          await this.getAllProducts();
          this.filterProducts();
        } else {
          ElMessage.error(data.msg || '添加失败');
        }
      } catch (error) {
        console.error('提交表单失败', error);
        if (error.name !== 'Error') {
          return; // 表单验证失败
        }
        // 忽略取消操作的错误
        if (error.toString().indexOf('cancel') === -1) {
          ElMessage.error(error.message || '操作失败');
        }
      }
    },

    /**
     * 图片上传成功处理
     */
    handleUploadSuccess(response) {
      if (response.code === 200) {
        this.form.imgSrc = response.data;
        ElMessage.success('图片上传成功');
      } else {
        ElMessage.error(response.msg || '图片上传失败');
      }
    },

    /**
     * 图片上传前验证
     */
    beforeUpload(file) {
      const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJpgOrPng) {
        ElMessage.error('只能上传JPG/PNG格式的图片');
        return false;
      }
      if (!isLt2M) {
        ElMessage.error('图片大小不能超过2MB');
        return false;
      }
      return true;
    },
    // 处理图片路径，适配 Vite 环境
    getImageUrl(imgSrc) {
      // 如果没有图片路径，返回默认图片
      if (!imgSrc) {
        return new URL('../assets/default-product.png', import.meta.url).href;
      }

      // 检查是否已经是完整路径（如http开头）
      if (imgSrc.startsWith('http://') || imgSrc.startsWith('https://')) {
        return imgSrc;
      }

      // 处理assets中的图片
      try {
        // 假设图片存放在assets/images/products目录下
        return new URL(`../assets/${imgSrc}`, import.meta.url).href;
      } catch (error) {
        console.error(`图片${imgSrc}加载失败`, error);
        return new URL('../assets/default-product.png', import.meta.url).href;
      }
    },
  }
};
</script>

<style scoped>
.product-container {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: calc(100vh - 40px);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.search-form {
  margin-bottom: 20px;
  padding: 15px;
  background-color: #fff;
  border-radius: 4px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.pagination {
  margin-top: 20px;
  text-align: right;
}

.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
  border-radius: 4px;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  background-color: #f5f7fa;
}

/* 表格悬停效果优化 */
::v-deep .el-table tbody tr:hover > td {
  background-color: #f5f7fa !important;
}

/* 按钮样式优化 */
::v-deep .el-button--small {
  margin-right: 5px;
}

/* 弹窗表单间距优化 */
::v-deep .el-form-item {
  margin-bottom: 15px;
}

/* 商品选择器下拉列表样式优化 */
::v-deep .el-select {
  width: 100%;
}

/* 调试信息样式 */
.debug-info {
  font-size: 12px;
  color: #666;
  margin-top: 5px;
  padding: 5px;
  background-color: #f5f5f5;
  border-radius: 4px;
}
/* 添加图片加载失败的样式 */
.image-placeholder {
  width: 60px;
  height: 60px;
  background-color: #f5f5f5;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #ccc;
}
</style>

